import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/models/travel_log_model.dart';
import '../../core/models/user_model.dart';
import '../../core/providers/travel_log_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/providers/follow_provider.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';

class ExploreRecordDetailView extends ConsumerStatefulWidget {
  final String recordIdentifier;

  const ExploreRecordDetailView({super.key, required this.recordIdentifier});

  @override
  ConsumerState<ExploreRecordDetailView> createState() =>
      _ExploreRecordDetailViewState();
}

class _ExploreRecordDetailViewState
    extends ConsumerState<ExploreRecordDetailView> {
  final TextEditingController _commentInputController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  bool _isCommentSubmitting = false;

  @override
  void dispose() {
    _commentInputController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final travelLogNotifier = ref.read(travelLogProvider.notifier);
    final currentUser = ref.watch(currentUserProvider);
    final isLoggedIn = ref.watch(isLoggedInProvider);

    final travelLog = travelLogNotifier.getLogById(widget.recordIdentifier);

    if (travelLog == null) {
      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.error_outline, size: 64, color: Colors.grey),
              SizedBox(height: 16.h),
              Text(
                'Travel log not found',
                style: TextStyle(fontSize: 18, color: Colors.grey[600]),
              ),
              SizedBox(height: 24.h),
              ElevatedButton(
                onPressed: () => GoRouter.of(context).pop(),
                child: Text('Go Back'),
              ),
            ],
          ),
        ),
      );
    }

    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();
    final authorInfo = allUsers.firstWhere(
      (user) => user.id == travelLog.userId,
      orElse: () => UserDataEntity.empty(),
    );

    final commentsList = travelLogNotifier.getLogComments(travelLog.logId);

    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          _buildMediaDisplaySection(travelLog),

          _buildContentContainer(
            travelLog,
            authorInfo,
            commentsList,
            isLoggedIn,
            currentUser,
          ),

          _buildTopNavigationBar(),

          _buildBottomCommentInput(isLoggedIn),
        ],
      ),
    );
  }

  Widget _buildMediaDisplaySection(TravelLogEntity travelLog) {
    final mediaHeight = 1.sh * (409 / 898);

    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: SizedBox(
        width: 1.sw,
        height: mediaHeight,
        child: Stack(
          fit: StackFit.expand,
          children: [
            Hero(
              tag: 'travel_log_image_${travelLog.logId}',
              child: Image.asset(
                travelLog.isVideoType && travelLog.videoCoverUrl != null
                    ? travelLog.videoCoverUrl!
                    : travelLog.mediaUrl,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.grey[300],
                    child:
                        Icon(
                          Icons.image_not_supported,
                          size: 64,
                          color: Colors.grey[600],
                        ).center(),
                  );
                },
              ),
            ),

            if (travelLog.isVideoType)
              Container(
                decoration: BoxDecoration(color: Colors.transparent),
                child:
                    Icon(
                      AliIcons.iconPlayFill,
                      size: 30.sp,
                      color: Colors.white,
                    ).center(),
              ).inkWell(onTap: () => _navigateToVideoPlayer(travelLog)),
          ],
        ),
      ),
    );
  }

  Widget _buildContentContainer(
    TravelLogEntity travelLog,
    UserDataEntity? authorInfo,
    List<TravelLogCommentEntity> commentsList,
    bool isLoggedIn,
    UserDataEntity? currentUser,
  ) {
    final containerHeight = 1.sh * (564 / 898);

    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.black,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(26.r),
            topRight: Radius.circular(26.r),
          ),
        ),
        padding: EdgeInsets.only(top: 3.w),
        child: Container(
          width: 1.sw,
          height: containerHeight,
          decoration: BoxDecoration(
            color: Color(0xFF2AB061),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(22.r),
              topRight: Radius.circular(22.r),
            ),
          ),
          child: SingleChildScrollView(
            controller: _scrollController,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 24.h),

                _buildUserInfoRow(authorInfo, isLoggedIn, currentUser),

                SizedBox(height: 20.h),

                _buildLogContentSection(travelLog),

                SizedBox(height: 20.h),

                _buildCommentTitle(),

                SizedBox(height: 16.h),

                _buildCommentsList(commentsList),

                SizedBox(height: 80.h),
              ],
            ).paddingHorizontal(20.w),
          ),
        ),
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: SafeArea(
        child: Container(
          height: 56.h,
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Row(
            children: [
              Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.black,
                ),
                child:
                    Icon(
                      Icons.arrow_back_ios_new,
                      color: Colors.white,
                      size: 20.sp,
                    ).center(),
              ).inkWell(onTap: () => GoRouter.of(context).pop()),

              Expanded(
                child: Text(
                  'Details',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 24.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily: 'PoetsenOne',
                  ),
                  textAlign: TextAlign.center,
                ),
              ),

              Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.black,
                ),
                child:
                    Icon(
                      AliIcons.iconReport,
                      color: Colors.white,
                      size: 22.sp,
                    ).center(),
              ).inkWell(onTap: () => _showTravelLogReportDialog()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildBottomCommentInput(bool isLoggedIn) {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: EdgeInsets.only(
          left: 16.w,
          right: 16.w,
          top: 12.h,
          bottom: MediaQuery.of(context).padding.bottom + 12.h,
        ),
        decoration: BoxDecoration(color: Colors.transparent),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(28.r),
          ),
          padding: EdgeInsets.only(bottom: 2.w, right: 2.w),
          child: Container(
            height: 56.h,
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: BorderRadius.circular(28.r),
              border: Border.all(color: Colors.black, width: 1.w),
            ),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _commentInputController,
                    enabled: isLoggedIn,
                    decoration: InputDecoration(
                      hintText:
                          isLoggedIn
                              ? 'say something...'
                              : 'Please login to comment',
                      hintStyle: TextStyle(
                        color: Colors.grey[500],
                        fontSize: 14.sp,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 12.h,
                      ),
                    ),
                    style: TextStyle(fontSize: 14.sp),
                    maxLines: 3,
                    minLines: 1,
                  ),
                ),

                Container(
                  width: 40.w,
                  height: 40.h,
                  margin: EdgeInsets.only(right: 4.w),
                  decoration: BoxDecoration(
                    color: isLoggedIn ? Color(0xFFFDDB31) : Colors.grey[400],
                    shape: BoxShape.circle,
                  ),
                  child:
                      _isCommentSubmitting
                          ? SizedBox(
                            width: 20.w,
                            height: 20.h,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(
                                Colors.white,
                              ),
                            ),
                          ).center()
                          : Icon(
                            AliIcons.iconSend,
                            color: Colors.white,
                            size: 22.sp,
                          ).center(),
                ).inkWell(
                  onTap:
                      isLoggedIn && !_isCommentSubmitting
                          ? () => _submitComment()
                          : () => _showLoginPrompt(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildUserInfoRow(
    UserDataEntity? authorInfo,
    bool isLoggedIn,
    UserDataEntity? currentUser,
  ) {
    if (authorInfo == null || !authorInfo.isValid) {
      return Container(
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Color(0xFFFDF5E1),
          borderRadius: BorderRadius.circular(58.r),
        ),
        child: Row(
          children: [
            CircleAvatar(
              radius: 27.r,
              backgroundColor: Colors.grey[300],
              child: Icon(Icons.person, color: Colors.grey[600]),
            ),
            SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Unknown User',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    'User information not available',
                    style: TextStyle(color: Colors.black, fontSize: 12.sp),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
    }

    final isCurrentUser = currentUser?.id == authorInfo.id;
    final followNotifier = ref.read(userFollowProvider.notifier);
    final isFollowing =
        isLoggedIn && currentUser != null
            ? followNotifier.isFollowing(currentUser.id, authorInfo.id)
            : false;

    return Container(
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(58.r),
      ),
      padding: EdgeInsets.only(right: 2.w, bottom: 2.w),
      child: Container(
        padding: EdgeInsets.all(10.w),
        decoration: BoxDecoration(
          color: Color(0xFFFDF5E1),
          borderRadius: BorderRadius.circular(58.r),
          border: Border.all(width: 1.w, color: Colors.black),
        ),
        child: Row(
          children: [
            GestureDetector(
              onTap: () {
                if (!isCurrentUser) {
                  GoRouter.of(
                    context,
                  ).push('/other-user-profile/${authorInfo.id}');
                }
              },
              child: CircleAvatar(
                radius: 27.r,
                backgroundImage:
                    authorInfo.avatar.isNotEmpty
                        ? AssetImage(authorInfo.avatar)
                        : null,
                backgroundColor: Colors.grey[300],
                child:
                    authorInfo.avatar.isEmpty
                        ? Icon(Icons.person, color: Colors.grey[600])
                        : null,
              ),
            ),

            SizedBox(width: 16),

            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    authorInfo.username.isNotEmpty
                        ? authorInfo.username
                        : 'ANNE',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w600,
                      fontFamily: 'PoetsenOne',
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    authorInfo.description.isNotEmpty
                        ? authorInfo.description
                        : 'Event publisher',
                    style: TextStyle(color: Colors.black, fontSize: 12.sp),
                    maxLines: 1,
                  ),
                ],
              ),
            ),

            if (!isCurrentUser)
              Container(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                decoration: BoxDecoration(
                  color: isFollowing ? Colors.grey : Colors.yellow,
                  borderRadius: BorderRadius.circular(20.r),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      isFollowing ? 'Following' : '+Follow',
                      style: TextStyle(
                        color: isFollowing ? Colors.black : Colors.white,
                        fontSize: 18.sp,
                        fontFamily: 'PoetsenOne',
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
              ).inkWell(
                onTap:
                    () => _handleFollowAction(
                      authorInfo,
                      isLoggedIn,
                      currentUser,
                    ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildLogContentSection(TravelLogEntity travelLog) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(12.r),
      ),
      padding: EdgeInsets.only(bottom: 2.w, right: 2.w),
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Color(0xFFFDF5E1),
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(width: 1.w, color: Colors.black),
        ),
        child: Text(
          travelLog.content,
          style: TextStyle(
            color: Colors.black.withValues(alpha: 0.60),
            fontSize: 14.sp,
            height: 1.5,
          ),
        ),
      ),
    );
  }

  Widget _buildCommentTitle() {
    return Text(
      'Comment',
      style: TextStyle(
        color: Colors.white,
        fontSize: 24.sp,
        fontFamily: 'PoetsenOne',
        fontWeight: FontWeight.w600,
      ),
    );
  }

  Widget _buildCommentsList(List<TravelLogCommentEntity> commentsList) {
    if (commentsList.isEmpty) {
      return Container(
        padding: EdgeInsets.all(32.w),
        child: Column(
          children: [
            Icon(
              Icons.chat_bubble_outline,
              size: 48.sp,
              color: Colors.white.withAlpha(150),
            ),
            SizedBox(height: 16.h),
            Text(
              'No comments yet',
              style: TextStyle(
                color: Colors.white.withAlpha(200),
                fontSize: 16.sp,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              'Be the first to share your thoughts!',
              style: TextStyle(
                color: Colors.white.withAlpha(150),
                fontSize: 12.sp,
              ),
            ),
          ],
        ),
      );
    }

    return Column(
      children:
          commentsList.map((comment) => _buildCommentItem(comment)).toList(),
    );
  }

  Widget _buildCommentItem(TravelLogCommentEntity comment) {
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();
    final commentUser = allUsers.firstWhere(
      (user) => user.id == comment.userId,
      orElse: () => UserDataEntity.empty(),
    );

    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          GestureDetector(
            onTap: () {
              final currentUser = ref.read(userProvider);
              // 如果不是当前用户，则跳转到他人页面
              if (currentUser?.id != commentUser.id) {
                GoRouter.of(
                  context,
                ).push('/other-user-profile/${commentUser.id}');
              }
            },
            child: CircleAvatar(
              radius: 19.r,
              backgroundImage:
                  commentUser.avatar.isNotEmpty
                      ? AssetImage(commentUser.avatar)
                      : null,
              backgroundColor: Colors.grey[300],
              child:
                  commentUser.avatar.isEmpty
                      ? Icon(Icons.person, color: Colors.grey[600], size: 20.sp)
                      : null,
            ),
          ),

          SizedBox(width: 12),

          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      commentUser.username.isNotEmpty
                          ? commentUser.username
                          : 'Dulce',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    Spacer(),

                    Icon(
                      Icons.more_horiz,
                      color: Colors.white.withAlpha(200),
                      size: 20.sp,
                    ).inkWell(onTap: () => _showCommentOptions(comment)),
                  ],
                ),

                SizedBox(height: 4.h),

                Text(
                  comment.content,
                  style: TextStyle(
                    color: Colors.white.withAlpha(230),
                    fontSize: 13.sp,
                    height: 1.4,
                  ),
                ),

                SizedBox(height: 8.h),

                Text(
                  _formatCommentTime(comment.createdTime),
                  style: TextStyle(
                    color: Colors.white.withAlpha(200),
                    fontSize: 11.sp,
                  ),
                ).alignRight(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _navigateToVideoPlayer(TravelLogEntity travelLog) {
    GoRouter.of(context).push('/video-player/${travelLog.logId}');
  }

  void _handleFollowAction(
    UserDataEntity authorInfo,
    bool isLoggedIn,
    UserDataEntity? currentUser,
  ) async {
    if (!isLoggedIn || currentUser == null) {
      _showLoginPrompt();
      return;
    }

    if (currentUser.id == authorInfo.id) {
      ToastHelper.info('You cannot follow yourself', context: context);
      return;
    }

    final followNotifier = ref.read(userFollowProvider.notifier);
    final isFollowing = followNotifier.isFollowing(
      currentUser.id,
      authorInfo.id,
    );

    try {
      bool success;
      if (isFollowing) {
        success = await followNotifier.unfollowUser(
          followerId: currentUser.id,
          followeeId: authorInfo.id,
        );
        if (mounted) {
          if (success) {
            ToastHelper.success('Unfollowed successfully', context: context);
          } else {
            ToastHelper.error('Failed to unfollow', context: context);
          }
        }
      } else {
        success = await followNotifier.followUser(
          followerId: currentUser.id,
          followeeId: authorInfo.id,
        );
        if (mounted) {
          if (success) {
            ToastHelper.success('Followed successfully', context: context);
          } else {
            ToastHelper.error('Failed to follow', context: context);
          }
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Operation failed', context: context);
      }
    }
  }

  void _submitComment() async {
    final content = _commentInputController.text.trim();
    if (content.isEmpty) {
      ToastHelper.info('Please enter your comment', context: context);
      return;
    }

    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      _showLoginPrompt();
      return;
    }

    setState(() {
      _isCommentSubmitting = true;
    });

    try {
      final travelLogNotifier = ref.read(travelLogProvider.notifier);
      final success = await travelLogNotifier.addComment(
        logId: widget.recordIdentifier,
        userId: currentUser.id,
        content: content,
      );

      if (mounted) {
        if (success) {
          _commentInputController.clear();
          ToastHelper.success('Comment posted successfully', context: context);
          setState(() {});
        } else {
          ToastHelper.error('Failed to post comment', context: context);
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to post comment', context: context);
      }
    } finally {
      if (mounted) {
        setState(() {
          _isCommentSubmitting = false;
        });
      }
    }
  }

  void _showLoginPrompt() {
    PopupHelper.showLoginDialog(
      context,
      onLoginPressed: () {
        context.push('/login');
      },
    );
  }

  String _formatCommentTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inMinutes < 1) {
      return 'Just now';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes}minutes ago';
    } else if (difference.inHours < 24) {
      return '${difference.inHours}hours ago';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}days ago';
    } else {
      return '${time.day}/${time.month}/${time.year}';
    }
  }

  void _showCommentOptions(TravelLogCommentEntity comment) {
    PopupHelper.showReportDialog(
      context,
      onReportSubmitted: (reportType) async {
        await _deleteComment(comment);
      },
      onCancelPressed: () {},
    );
  }

  void _showTravelLogReportDialog() {
    PopupHelper.showReportDialog(
      context,
      onReportSubmitted: (reportType) async {
        await _deleteTravelLog();
      },
      onCancelPressed: () {},
    );
  }

  Future<void> _deleteComment(TravelLogCommentEntity comment) async {
    try {
      final travelLogNotifier = ref.read(travelLogProvider.notifier);
      final success = await travelLogNotifier.deleteComment(comment.commentId);

      if (mounted) {
        if (success) {
          ToastHelper.success(
            'Report submitted successfully',
            context: context,
          );
          setState(() {});
        } else {
          ToastHelper.error('Failed to delete comment', context: context);
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to delete comment', context: context);
      }
    }
  }

  Future<void> _deleteTravelLog() async {
    try {
      final travelLogNotifier = ref.read(travelLogProvider.notifier);
      final success = await travelLogNotifier.deleteTravelLog(
        widget.recordIdentifier,
      );

      if (mounted) {
        if (success) {
          ToastHelper.success(
            'Report submitted successfully',
            context: context,
          );
          GoRouter.of(context).pop();
        } else {
          ToastHelper.error('Failed to delete travel log', context: context);
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to delete travel log', context: context);
      }
    }
  }
}
